

<template>
  <div class="search-address back-page">
    <HeaderTop>
      <template #left>
        <van-icon name="arrow-left" @click="router.back()" class="m-return-icon" size="23" />
      </template>
      <template #center>
        选择地址
      </template>
    </HeaderTop>
    <div class="back-page py-3">
      <van-form @failed="onFailed" @submit="submit" class="center" style="width: 90%">
        <van-cell-group inset>
          <!-- 通过 pattern 进行正则校验 -->
          <van-field
            input-align="center"
            class="w-100"
            v-model="address"
            name="pattern"
            placeholder="输入学校、商务楼、地址"
            :rules="[{ required: true, message: '地址不能为空' }]"
        /></van-cell-group>
        <div style="margin-top: 16px">
          <van-button round block type="primary" native-type="submit"> 提交 </van-button>
        </div></van-form
      >
    </div>
    <div v-for="item in searchList" @click="selectAddress(item)"  :key="item.name" class="m-search-list">
      <div class="my-4 mx-3 fs-4">{{ item.name }}</div>
      <div class="my-4 mx-3 fs-6 text-3">{{ item.address }}</div>
    </div>
    <van-empty v-if="isSearched&&!searchList.length" image="search" description="搜索不到啊" />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { search } from "@/type/index";
import { searchNearByAddress} from "@/api";
import { Notify } from "vant";
import { useRouter } from "vue-router";
import { constPinia } from "@/store/index";
import { storeToRefs } from "pinia";


const router = useRouter();

const store = constPinia();
const {nearByAddress}  = storeToRefs(store)

//输入的地址
const address = ref<string>();
const onFailed = errorInfo => {
  Notify({ type: "warning", message: "地址不能为空" });
};
////搜索列表
const searchList = ref<search>();
const searchData = async () => {
  const res = await searchNearByAddress<search>( address.value);
  searchList.value = res;
  console.log(res);
  isSearched.value = true;
};
//是否是搜索完成
const isSearched = ref<boolean>(false);
watch(address, () => {
  if (!address.value) {
    isSearched.value = false;
    router.back()
  }
});

//确认搜索
const submit = () => {
  searchData();
};
//选中地址
const selectAddress = address => {
  nearByAddress.value = address
  router.back()
};

</script>

<style lang="scss" scoped>
@import "@/assets/scss/mixin.scss";
.search-address {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 23;
  overflow-x: hidden;
}
.m-return-icon {
  transform: translate(-0.3rem);
}
.m-search-list {
  border-bottom: 0.02rem solid $Dark;
}
</style>
